<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑认证</title>
    <link rel="stylesheet" href="//unpkg.com/element-ui@2.15.13/lib/theme-chalk/index.css">
    <script src="//unpkg.com/vue@2.6.11/dist/vue.min.js"></script>
    <script src="//unpkg.com/axios@0.19.2/dist/axios.min.js"></script>
    <script src="//unpkg.com/element-ui@2.15.13/lib/index.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #f5f7fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        #app {
            padding: 20px;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            width: 100%;
        }
        .el-card {
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        }
        .el-form {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
        }
        /* 响应式设计 */
        @media (max-width: 1200px) {
            .container {
                max-width: 100%;
            }
        }
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            .el-form {
                padding: 20px;
            }
        }
        .file-item {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ebeef5;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 15px;
            background-color: #fafafa;
            transition: all 0.3s ease;
        }
        .file-item:hover {
            border-color: #409eff;
            background-color: #f0f7ff;
        }
        .file-item img {
            max-width: 100px;
            max-height: 100px;
            border-radius: 6px;
            border: 1px solid #ebeef5;
            object-fit: cover;
        }
        .file-info {
            flex: 1;
        }
        .actions {
            display: flex;
            gap: 10px;
        }
        .upload-demo {
            margin-top: 12px;
        }
        .el-upload-list {
            max-width: 400px;
        }
        .el-form-item {
            margin-bottom: 25px;
        }
        .el-form-item__label {
            font-weight: 500;
        }
        .el-button {
            transition: all 0.3s ease;
        }
        /* 确保输入框样式稳定 */
        .el-input__inner {
            transition: border-color 0.2s ease;
        }
        /* 优化上传组件样式 */
        .el-upload-list__item {
            margin-bottom: 8px;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="container">
            <el-card shadow="never">
                <div slot="header" class="clearfix">
                    <span>{{ isEdit ? '编辑认证' : '新增认证' }}</span>
                    <el-button type="primary" @click="save" style="float: right;">保存</el-button>
                </div>
            </el-card>

            <el-form :model="formData" :rules="rules" ref="form" label-width="120px">
                <el-form-item label="认证名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入认证名称" maxlength="255"></el-input>
                </el-form-item>

                <el-form-item label="用户ID" prop="user_id">
                    <el-select v-model.number="formData.user_id" placeholder="请选择用户" filterable>
                        <el-option v-for="user in userList" :key="user.id" :label="`ID:${user.id} 名称: ${user.name}`" :value="user.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="领域ID" prop="cate_id">
                    <el-select v-model.number="formData.cate_id" placeholder="请选择领域" filterable>
                        <el-option v-for="cate in cateList" :key="cate.id" :label="`${cate.name} (ID: ${cate.id})`" :value="cate.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-select v-model.number="formData.status" placeholder="请选择状态">
                        <el-option :label="'未审核'" :value="0"></el-option>
                        <el-option :label="'通过'" :value="1"></el-option>
                        <el-option :label="'拒绝'" :value="2"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="描述" prop="describe">
                    <el-input v-model="formData.describe" placeholder="请输入描述" type="textarea" rows="4" maxlength="5000" show-word-limit></el-input>
                </el-form-item>

                <el-form-item label="认证资料">
                    <div>
                        <div v-for="(item, index) in formData.information_json" :key="index" class="file-item">
                            <img :src="item.file.replace(/`/g, '')" v-if="item.file">
                            <div class="file-info">
                                <el-input v-model="item.name" placeholder="资料名称" style="margin-bottom: 5px;"></el-input>
                                <el-upload
                                    class="upload-demo"
                                    action="/file/upload/image"
                                    :on-success="(response, file, fileList) => handleUploadSuccess(response, file, index)"
                                    :on-error="handleUploadError"
                                    :on-remove="() => handleRemoveFile(index)"
                                    :before-upload="beforeUpload"
                                    :limit="1"
                                  
                                    :show-file-list="true"
                                    accept="image/*"
                                >
                                <!-- :file-list="getCurrentFileList(index)" -->
                                    <el-button size="small" type="primary">点击上传</el-button>
                                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
                                </el-upload>
                            </div>
                            <div class="actions">
                                <el-button type="danger" icon="el-icon-delete" @click="removeFile(index)"></el-button>
                            </div>
                        </div>
                        <el-button type="primary" @click="addFile" icon="el-icon-plus">添加资料</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </div>

    <script>
        // 获取URL参数
        function getUrlParam(name) {
            const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
            const r = window.location.search.substr(1).match(reg);
            if (r !== null) return decodeURIComponent(r[2]);
            return null;
        }

        new Vue({
            el: '#app',
            data() {
                return {
                    isEdit: false,
                    formData: {
                        id: '',
                        name: '',
                        user_id: '',
                        cate_id: '',
                        information_json: [],
                        status: 0, // 状态:0=未审核,1=通过,2=拒绝
                        describe: '' // 描述
                    },
                    userList: [], // 用户列表数据
                    cateList: [], // 领域列表数据
                    rules: {
                        name: [
                            { required: true, message: '请输入认证名称', trigger: 'blur' }
                        ],
                        user_id: [
                            { required: true, message: '请输入用户ID', trigger: 'blur' },
                            { type: 'number', message: '用户ID必须是数字', trigger: 'blur' }
                        ],
                        cate_id: [
                            { required: true, message: '请输入领域ID', trigger: 'blur' },
                            { type: 'number', message: '领域ID必须是数字', trigger: 'blur' }
                        ],
                        status: [
                            { type: 'number', message: '状态必须是数字', trigger: 'blur' }
                        ],
                        describe: [
                            { max: 5000, message: '描述最多5000个字符', trigger: 'blur' }
                        ]
                    }
                };
            },
            created() {
                // 获取用户列表
                this.fetchUserList();
                // 获取领域列表
                this.fetchCateList();
                
                const id = getUrlParam('id');
                if (id) {
                    this.isEdit = true;
                    this.formData.id = id;
                    this.fetchDetail();
                } else {
                    // 默认添加一个资料项
                    this.addFile();
                }
            },
            methods: {
                // 获取领域列表
                fetchCateList() {
                    axios.get('/science/cate/lists')
                        .then(res => {
                            if (res.data && !res.data.error && res.data.data) {
                                this.cateList = res.data.data;
                            } else {
                                this.$message.error('获取领域列表失败');
                            }
                        })
                        .catch(err => {
                            console.error('获取领域列表出错:', err);
                            this.$message.error('获取领域列表出错');
                        });
                },
                // 获取用户列表
                fetchUserList() {
                    axios.get('/admin/user.user/lists')
                        .then(res => {
                            if (res.data && !res.data.error && res.data.data) {
                                this.userList = res.data.data;
                            } else {
                                this.$message.error('获取用户列表失败');
                            }
                        })
                        .catch(err => {
                            console.error('获取用户列表出错:', err);
                            this.$message.error('获取用户列表出错');
                        });
                },
                fetchDetail() {
                    axios.get('/science/authentication/detail', { params: { id: this.formData.id } })
                        .then(res => {
                            if (res.data && !res.data.error && res.data.data) {
                                const data = res.data.data;
                                this.formData.name = data.name || '';
                                this.formData.user_id = data.user_id || '';
                                this.formData.cate_id = data.cate_id || '';
                                this.formData.status = data.status !== undefined ? data.status : 0;
                                this.formData.describe = data.describe || '';
                                // 处理认证资料
                                if (data.information_json) {
                                    if (Array.isArray(data.information_json)) {
                                        this.formData.information_json = data.information_json;
                                    } else if (typeof data.information_json === 'string') {
                                        try {
                                            this.formData.information_json = JSON.parse(data.information_json);
                                        } catch (e) {
                                            console.error('解析认证资料失败:', e);
                                            this.formData.information_json = [];
                                        }
                                    } else {
                                        this.formData.information_json = [];
                                    }
                                }
                                // 如果没有资料，添加一个空项
                                if (!this.formData.information_json || this.formData.information_json.length === 0) {
                                    this.addFile();
                                }
                            } else {
                                this.$message.error(res.data.msg || '获取详情失败');
                            }
                        })
                        .catch(err => {
                            console.error('获取详情失败:', err);
                            this.$message.error('获取详情失败');
                        });
                },
                
                addFile() {
                    this.formData.information_json.push({
                        name: '',
                        file: ''
                    });
                },
                
                removeFile(index) {
                    this.$confirm('确定要删除这条资料吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.formData.information_json.splice(index, 1);
                        // 确保至少有一个资料项
                        if (this.formData.information_json.length === 0) {
                            this.addFile();
                        }
                    }).catch(() => {
                        // 取消删除
                    });
                },
                
                // 上传成功处理
                handleUploadSuccess(response, file, index) {
                    if (response && !response.error && response.data && response.data.url) {
                        this.formData.information_json[index].file = response.data.url;
                        this.$message.success('上传成功');
                    } else {
                        this.$message.error(response.msg || '上传失败');
                    }
                },
                
                // 上传失败处理
                handleUploadError(err) {
                    console.error('上传失败:', err);
                    this.$message.error('上传失败，请重试');
                },
                
                // 移除上传文件处理
                handleRemoveFile(index) {
                    this.formData.information_json[index].file = '';
                },
                
                // 文件上传前检查
                beforeUpload(file) {
                    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                    const isLt2M = file.size / 1024 / 1024 < 2;

                    if (!isJPG) {
                        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
                    }
                    if (!isLt2M) {
                        this.$message.error('上传头像图片大小不能超过 2MB!');
                    }
                    return isJPG && isLt2M;
                },
                
                // 获取当前项的文件列表（用于显示已上传的文件）
                getCurrentFileList(index) {
                    // 使用独立的引用获取文件信息，避免与item.name的响应式关联
                    const fileUrl = this.formData.information_json[index]?.file;
                    if (fileUrl) {
                        return [{
                            name: '上传的图片',
                            url: fileUrl
                        }];
                    }
                    return [];
                },
                
                save() {
                    this.$refs.form.validate((valid) => {
                        if (valid) {
                            // 验证认证资料
                            let hasEmptyFile = false;
                            this.formData.information_json.forEach(item => {
                                if (!item.name || !item.file) {
                                    hasEmptyFile = true;
                                }
                            });
                            
                            if (hasEmptyFile) {
                                this.$message.error('请填写完整的认证资料');
                                return;
                            }
                            
                            const url = this.isEdit ? '/science/authentication/update' : '/science/authentication/add';
                            const data = {
                                ...this.formData
                            };
                            
                            axios.post(url, data)
                                .then(res => {
                                    if (res.data && !res.data.error) {
                                        this.$message.success('保存成功');
                                        setTimeout(() => {
                                            window.location.href = '/super#/science/authentication/index';
                                        }, 1500);
                                    } else {
                                        this.$message.error(res.data.msg || '保存失败');
                                    }
                                })
                                .catch(err => {
                                    console.error('保存失败:', err);
                                    this.$message.error(res.message || '保存失败');
                                });
                        }
                    });
                }
            }
        });
    </script>
</body>
</html>